<template>
    <div class="exam-container">
        <nav-bar title="试卷"></nav-bar>
        <div class="exam-wrap">
            <div class="count-down">
                距离考试还剩：
                <van-count-down ref="countDown" :time="time" @finish="finish"/>
            </div>
            <div class="line-box">
                <div class="line" :style="{ width: (activeIdx / list.length) * 100 + '%' }"></div>
            </div>
            <div class="media-wrap"></div>
            <!-- <Media
            v-if="answerList[activeIdx - 1].content.attachment&&answerList[activeIdx - 1].content.attachment.length"
            :data="answerList[activeIdx - 1].content.attachment"
            ></Media>-->
            <div class="exam-content">
                <div class="loading-wrap" v-show="loading">
                    <van-loading/>
                </div>
                <transition name="slide-fade">
                    <div
                        class="Router"
                        ref="Router"
                        id="Router"
                        :key="list[activeIdx - 1].questionBankId"
                        v-if="(activeIdx > 0) & !loading"
                    >
                        <p class="ques-name">
                            第{{ activeIdx }}题
                            <span
                                v-if="activeIdx > 0"
                            >({{ typeName[answerList[activeIdx - 1].type] }})</span>
                        </p>

                        <div
                            class="question-wrap"
                            v-for="(content, index) in qesComponents"
                            :key="index"
                        >
                            <!-- component标签创建动态组件，is属性指向谁，就显示哪个组件 -->

                            <component
                                class="question-compents"
                                :key="list[activeIdx - 1].questionBankId"
                                :is="content.component"
                                ref="q"
                                :refName="content.refName"
                                :data="answerList[activeIdx - 1]"
                                v-if="
									activeIdx != 0 &&
									content.refName == Type[list[activeIdx - 1].questionType]
								"
                                @changeValue="changeValue"
                                @nextQues="next"
                            >
                                <btn
                                    class="btn"
                                    @click="next"
                                >{{ answerList.length === activeIdx ? "交卷" : "下一题" }}</btn>
                            </component>
                        </div>
                    </div>
                </transition>
            </div>
            <answer-card
                ref="AnswerCard"
                :list="list"
                :answerList="answerList"
                @backTo="backTo"
                :playback="!examInfo.playback || examInfo.playback === 'PLAY_BACK'"
            ></answer-card>
            <div class="fixed-btn" @click="openCard">试题序号</div>
        </div>
    </div>
</template>
<script>
import Media from "@/components/Media";
import AnswerCard from "@/components/AnswerCard";
import { decode, encode } from "@/common/utils/crypto";
import { qesComponents, Type } from "@/components/Questions";
import { mapState, mapMutations } from "vuex";
import { setTimeout } from "timers";
import { randomBytes } from "crypto";

import randomArray from "@/common/utils/randomArray";
export default {
    name: "exam",
    components: {
        AnswerCard,
        Media,
    },
    data() {
        return {
            transitionName: "slide-right",
            timer: null,
            qesComponents: [], //试题类型
            Type: [],
            loading: true,
            train: 0,
            typeName: {
                TypeA1: "A1题",
                TypeA2: "A2题",
                TypeA3: "A3题",
                TypeA4: "A4题",
                TypeB1: "B1题",
                TypeM1: "M1题",
                TypeSingleChoice: "单选题",
                TypeMultipleChoice: "多选题",
                TypeJudge: "判断题",
                TypeSort: "排序题",
                TypeEssay: "填空题",
                TypeFlow: "系列题",
                TypeWork: "应用题",
                TypeSubjective: "主观题",
                TypeExplanation: "名词解释题",
            },
        };
    },
    computed: {
        ...mapState({
            examId: state => state.exam.examId,
            time: state => state.exam.time,
            list: state => state.exam.list,
            activeIdx: state => state.exam.activeIdx,
            answerList: state => state.exam.answerList,
            examInfo: state => state.exam.examInfo,
            startTime: state => state.exam.startTime,
        }),
    },
    beforeRouteLeave(to, from, next) {
        clearInterval(this.timer);
        next(vm => {});
    },
    mounted() {
        var that = this;
        this.train = this.$route.query.train;
        this.qesComponents = qesComponents;
        this.Type = Type;
        if (this.examId === this.$route.query.examId) {
            this.loading = false;
        } else {
            this.SET_time(this.$route.query.time * 1000);
            this.SET_examId(this.$route.query.examId);
            this.getExamDes();
            this.SET_startTime(new Date().getTime());
        }

        this.timer = setInterval(() => {
            this.SET_time(that.$refs.countDown.getRemain());
        }, 1000);
    },
    methods: {
        ...mapMutations({
            SET_examId: "exam/SET_examId",
            SET_time: "exam/SET_time",
            SET_activeIdx: "exam/SET_activeIdx",
            SET_list: "exam/SET_list",
            SET_answerList: "exam/SET_answerList",
            CLEAR_EXAM: "exam/CLEAR_EXAM",
            SET_startTime: "exam/SET_startTime",
        }),
        getExamDes() {
            this.$APIs[this.train ? "getTrainDes" : "getExamDes"]({
                examId: this.$route.query.examId,
            })
                .then(response => {
                    this.SET_list(response);
                    this.SET_answerList(new Array(response.length));
                    this.renderQes(this.activeIdx);
                    this.$toast("考试开始");
                })
                .catch(error => {});
        },
        openCard() {
            this.$refs.AnswerCard.activeIdx = this.activeIdx - 1;
            this.$refs.AnswerCard.showPopup = true;
        },
        next() {
            if (this.loading) {
                return;
            }
            if (this.answerList.length === this.activeIdx) {
                this.submitExam();
            } else {
                if (this.examInfo.playback == "NO_BACK") {
                    this.$dialog
                        .confirm({
                            message: "确认后不可返回本道题目",
                        })
                        .then(() => {
                            this.saveScore(this.activeIdx);
                        })
                        .catch(() => {
                            // on cancel
                        });
                } else {
                    this.saveScore(this.activeIdx);
                }
            }
        },
        getUseTime() {
            return (this.$route.query.time * 1000 - this.$refs.countDown.getRemain()) / 1000;
        },
        submitExam() {
            if (!this.answerList.length) {
                this.$toast("试题列表不存在");
                this.$router.back();
                return;
            }
            this.$dialog
                .confirm({
                    message: "确认交卷",
                })
                .then(() => {
                    var obj;

                    if (this.train) {
                        obj = {
                            startTime: this.startTime,
                            endTime: new Date().getTime(),
                            examId: this.$route.query.examId,
                            timeUse: this.getUseTime(),
                        };
                    } else {
                        obj = {
                            examId: this.$route.query.examId,
                            timeUse: this.getUseTime(),
                        };
                    }
                    this.$APIs[this.train ? "submitTrain" : "submitExam"](obj)
                        .then(response => {
                            this.$toast("试卷提交成功");
                            this.$router.back();
                            this.CLEAR_EXAM();
                        })
                        .catch(error => {});
                })
                .catch(() => {
                    // on cancel
                });
        },
        finish() {
            if (this.getUseTime() > 1) {
                this.$toast("考试结束");
                this.$dialog
                    .alert({
                        message: "考试时间结束",
                    })
                    .then(() => {
                        var obj;
                        if (this.train) {
                            obj = {
                                startTime: this.startTime,
                                endTime: new Date().getTime(),
                                examId: this.$route.query.examId,
                                timeUse: this.getUseTime(),
                            };
                        } else {
                            obj = {
                                examId: this.$route.query.examId,
                                timeUse: this.getUseTime(),
                            };
                        }
                        this.$APIs[this.train ? "submitTrain" : "submitExam"](obj)
                            .then(response => {
                                this.$toast("试卷提交成功");
                                this.$router.back();
                                this.CLEAR_EXAM();
                            })
                            .catch(error => {});
                    });
            }
        },
        backTo(data) {
            this.saveScore(data);
        },
        changeValue(answerC, contentC, scoreC) {
            var answerList = JSON.parse(JSON.stringify(this.answerList));
            var { answer, questionAnswerContent, score } = answerList[this.activeIdx - 1];
            answerList[this.activeIdx - 1].answer = answerC;
            answerList[this.activeIdx - 1].finish = contentC.finish;
            answerList[this.activeIdx - 1].questionAnswerContent =
                contentC === undefined ? questionAnswerContent : contentC;
            answerList[this.activeIdx - 1].score = scoreC === undefined ? score : encode(scoreC);
            this.SET_answerList(answerList);
        },
        saveScore(idx) {
            if (this.$refs["q"][0].changeValue()) {
                return;
            }
            this.$APIs[this.train ? "saveTrainScore" : "saveScore"]({
                examId: this.list[this.activeIdx - 1].examId,
                questionAnswerContent: JSON.stringify(
                    this.answerList[this.activeIdx - 1].questionAnswerContent,
                ),
                questionId: this.list[this.activeIdx - 1].questionId,
                score: this.answerList[this.activeIdx - 1].score || "",
            })
                .then(response => {
                    this.renderQes(idx);
                })
                .catch(error => {
                    if (error.code === 5009) {
                        this.$dialog
                            .alert({
                                message: "考试时间结束",
                            })
                            .then(() => {
                                this.$toast("试卷提交成功");
                                this.$router.back();
                                this.CLEAR_EXAM();
                            });
                    }
                });
        },
        renderQes(idx) {
            //参数为数组坐标

            if (this.answerList[idx]) {
                //已经下载过数据的题目
                this.SET_activeIdx(idx + 1);
                document.body.scrollTop = 0;
                document.documentElement.scrollTop = 0;
            } else {
                this.loading = true;
                this.$APIs[this.train ? "getTrainContent" : "getQuestionContent"]({
                    examId: this.list[idx].examId,
                    questionId: this.list[idx].questionId,
                })
                    .then(response => {
                        document.body.scrollTop = 0;
                        document.documentElement.scrollTop = 0;
                        var answerList = JSON.parse(JSON.stringify(this.answerList));
                        answerList[idx] = {
                            content: randomArray(
                                JSON.parse(decode(response.content)),
                                this.examInfo.questionAnsSort,
                                response.questionType,
                            ),
                            type: response.questionType,
                            answer: null,
                            index: this.activeIdx,
                            questionScore: response.questionScore,
                            totalScore: response.totalScore,
                        };
                        this.SET_answerList(answerList);
                        this.SET_activeIdx(idx + 1);
                        this.loading = false;
                    })
                    .catch(error => {
                        console.log(error);
                    });
            }
        },
    },
};
</script>

<style lang="scss">
.exam-container {
    height: 100%;
    display: flex;
    flex-direction: column;
    .line-box {
        margin: 20px auto 10px;
        background: #fff;
        width: 80%;
        height: 4px;
        border-radius: 5px;
        overflow: hidden;
        .line {
            background-color: #56baca;
            width: 0;
            height: 4px;
            transition: all 0.8s;
        }
    }
    .question-title {
        margin: 10px 0;
    }
    .ques-name {
        font-size: 18px;
        font-weight: bold;
    }
    .van-count-down {
        font-size: 18px;
        color: #56baca;
    }
    p {
        font-size: 15px;
    }
    .exam-content {
        padding: 15px 15px 0 15px;
        flex: 1;
    }
    .loading-wrap {
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 50px 0;
    }
    .title {
        font-size: 18px;
        margin: 0 0 20px;
    }
    .count-down {
        display: flex;
        justify-content: center;
        font-size: 18px;
        color: #56baca;
        margin: 15px 0 0;
    }
    .fixed-btn {
        background: #ecfabd;
        padding: 11px 14px;
        position: fixed;
        right: 0;
        bottom: 10%;
        z-index: 10;
        font-size: 12px;
        border-radius: 36px 0px 0px 36px;
        color: #000000;
    }
    video {
        border-radius: 10px;
        width: 100%;
    }
    .video-content {
        margin: 20px 0;
        display: flex;
        justify-content: center;
    }

    .van-radio__label {
        font-size: 15px;
        color: #fff;
    }
    .van-radio {
        margin-bottom: 15px;
    }
    .ques-title {
        font-size: 16px;
        margin: 20px 0;
    }
    .btn {
        margin: 40px 0 10px;
        // position: fixed;
        // bottom: 0;
        // left: 50%;
        // transform: translateX(-50%);
        // width: 80%;
    }

    .question-wrap {
        position: relative;
    }
    .exam-wrap {
        flex: 1;
        overflow-y: scroll;
        display: flex;
        flex-direction: column;
    }

    .Router {
        position: absolute;
        left: 0;
        top: 130px;
        width: 100%;
        transition: all 0.3s ease;
        overflow-y: scroll;
        padding: 15px;
    }

    .slide-fade-enter-active {
        transition: all 0.3s ease;
    }
    .slide-fade-leave-active {
        transition: all 0.3s ease;
    }
    .slide-fade-enter, .slide-fade-leave-to
/* .slide-fade-leave-active for below version 2.1.8 */ {
        //transform: translateX(10px);
        opacity: 0;
    }
}
</style>
